LSEG Tick History REST API in Python: download trades and quotes

API
Data Sources
Tutorial
Python
A Python script that downloads every trade and quote for a list of stocks from LSEG Tick History and restarts where it stopped.
Published

July 12, 2026

Updated

November 21, 2026

downloading tick data from LSEG Tick History in Python

This post is the same story as with my posts on IPO and insider trading data. I wrote a script to get tick data, and I want to share it with readers who have access to LSEG Tick History, which gives you every trade and quote, timestamped to the microsecond. You end up with every trade, quote, auction and correction, in one CSV file per stock per 30-day window. I use the London Stock Exchange as the example, but the script handles any exchange LSEG covers.

You need a Tick History username and password, of course, and you also need Python. And you also need Workspace if you start from a list of ISINs, because Step 1 uses Workspace to turn them into RICs, LSEG’s codes for the stocks. If you already have the RICs, you do not need Workspace.

Step 1. Turning instruments into RICs

If you already have RICs, put them in a list called rics and go to Step 2.

import pandas as pd
import lseg.data as ld
from lseg.data.content import symbol_conversion

ld.open_session()   # LSEG Workspace desktop must be running


def chunks(sequence, size):
    """Walk a list in slices, because the conversion service throttles large requests."""
    for start in range(0, len(sequence), size):
        yield sequence[start:start + size]


isins = [...]        # your list of ISINs
ric_map = {}         # ISIN -> RIC

for batch in chunks(isins, 250):
    resp = symbol_conversion.Definition(
        symbols=batch,
        from_symbol_type=symbol_conversion.SymbolTypes.ISIN,
        to_symbol_types=[symbol_conversion.SymbolTypes.RIC],
    ).get_data()
    converted = resp.data.df

    for isin in batch:
        if isin not in converted.index:
            continue                        # the service returned no RIC for this ISIN

        ric = converted.loc[isin, "RIC"]

        # An ISIN that maps to several RICs comes back as a Series rather than one value,
        # so .loc returns every match.
        if isinstance(ric, pd.Series):
            ric = ric.iloc[0]

        if pd.notna(ric):
            ric_map[isin] = str(ric)

# Drop the delisting suffix after the caret, then keep the London names.
base_names = [ric.split("^")[0] for ric in ric_map.values()]

# A set drops the duplicates two ISINs can produce, and sorted makes the run repeatable
rics = sorted({name for name in base_names if name.endswith(".L")})
print(f"Converted {len(ric_map)} ISINs, kept {len(rics)} London RICs")

A delisted stock’s RIC gets a suffix, such as TRIL.L^I09 for TRIL.L, delisted in September 2009, and the code drops it, which I have not verified for every case.

Step 2. Authenticating against Tick History

You send your username and password and get a token back, which every later call includes.

And keep your username and password safe. I cannot remember exactly how I did it, but you can store them in your computer’s environment variables, so if you accidentally send the script to someone, the only one who can see them is you.

import os

os.environ["RTH_USER"] = "YOUR_USERNAME"   # your DataScope user id
os.environ["RTH_PASS"] = "YOUR_PASSWORD"   # your DataScope password
import requests

BASE        = "https://selectapi.datascope.lseg.com/RestApi/v1"
AUTH_URL    = f"{BASE}/Authentication/RequestToken"
EXTRACT_URL = f"{BASE}/Extractions/ExtractRaw"

class RTHError(RuntimeError):
    pass

def auth_token():
    u, p = os.environ.get("RTH_USER"), os.environ.get("RTH_PASS")
    if not u or not p:
        raise RTHError("Set RTH_USER and RTH_PASS first.")
    r = requests.post(AUTH_URL, json={"Credentials": {"Username": u, "Password": p}})
    if r.status_code != 200:
        raise RTHError(f"AUTH {r.status_code}: {r.text[:500]}")
    token = r.json().get("value")
    if not token:
        raise RTHError("Authenticated, but no token came back.")
    return token

Step 3. Building the request

One request covers one stock over one date range, with the fields you want.

def payload_tas(ric, start, end, fields=None):
    fields = fields or [
        # Trade
        "Trade - Price", "Trade - Volume", "Trade - Exchange Time",
        "Trade - Qualifiers", "Trade - Exchange/Contributor ID",
        "Trade - Buyer ID", "Trade - Seller ID",
        "Trade - Trade Price Currency", "Trade - ISIN",
        # Auction
        "Auction - Price", "Auction - Volume", "Auction - Exchange Time",
        "Auction - Bid Price", "Auction - Bid Size",
        "Auction - Ask Price", "Auction - Ask Size", "Auction - Qualifiers",
        # Quote
        "Quote - Bid Price", "Quote - Bid Size",
        "Quote - Ask Price", "Quote - Ask Size", "Quote - Volume",
        "Quote - Exchange Time", "Quote - Qualifiers",
        "Quote - Exchange/Contributor ID",
        "Quote - Buyer ID", "Quote - Seller ID", "Quote - ISIN",
        # Correction
        "Correction - Bid Price", "Correction - Ask Price",
        "Correction - Exchange Time", "Correction - Exchange/Contributor ID",
        "Correction - Original Exchange Time", "Correction - ISIN",
    ]
    return {
        "ExtractionRequest": {
            "@odata.type": "#DataScope.Select.Api.Extractions.ExtractionRequests.TickHistoryTimeAndSalesExtractionRequest",
            "ContentFieldNames": fields,
            "IdentifierList": {
                "@odata.type": "#DataScope.Select.Api.Extractions.ExtractionRequests.InstrumentIdentifierList",
                "InstrumentIdentifiers": [{"Identifier": ric, "IdentifierType": "Ric"}],
                "ValidationOptions": {
                    "AllowHistoricalInstruments": True,   # keep delisted names
                    "AllowInactiveInstruments": True,
                    "AllowOpenAccessInstruments": True,
                },
                "UseUserPreferencesForValidationOptions": False,
            },
            "Condition": {
                "MessageTimeStampIn": "GmtUtc",
                "ApplyCorrectionsAndCancellations": True,
                "ReportDateRangeType": "Range",
                "QueryStartDate": start,
                "QueryEndDate":   end,
                "DisplaySourceRIC": True,
            },
        }
    }

AllowHistoricalInstruments keeps delisted stocks in the extraction. It is important to keep track of the delisted companies, because if you do not include them, it will bias your conclusion. The option does not add stocks to your list, so your list must also include stocks that traded in your dates and were delisted later.

Step 4. Downloading in windows, with retries

The reason why I cut the data into 30-day windows and save each one is to save space and memory. If you do not split your requests, the code becomes slower and slower because it holds bigger and bigger data in its memory, so you need to reset that by saving one part of the data at a time.

import io, json, zipfile

def _read_zip_or_csv_bytes(b: bytes) -> pd.DataFrame:
    if len(b) > 4 and b[:4] == b"PK\x03\x04":          # a ZIP file starts with these four bytes
        with zipfile.ZipFile(io.BytesIO(b)) as z:
            names = [n for n in z.namelist() if n.lower().endswith(".csv")] or z.namelist()
            if not names:
                raise RTHError("ZIP had no files.")
            with z.open(names[0]) as f:
                return pd.read_csv(f)
    return pd.read_csv(io.BytesIO(b))                   # otherwise a plain CSV

def _collect_links(j):
    urls = []
    for key in ("Notes", "notes"):
        for n in (j.get(key) or []):
            if isinstance(n, dict) and "URL" in n:
                urls.append(n["URL"])
    for c in (j.get("Contents") or []):
        if isinstance(c, dict) and "Location" in c:
            urls.append(c["Location"])
    return urls

def download_stream_by_jobid(token, job_id) -> pd.DataFrame:
    headers = {"Authorization": f"Token {token}"}
    url = f"{BASE}/Extractions/RawExtractionResults('{job_id}')/$value"
    r = requests.get(url, headers=headers, stream=True)
    if r.status_code >= 400:
        raise RTHError(f"DOWNLOAD {r.status_code}: {r.text[:800]}")
    return _read_zip_or_csv_bytes(r.content)

def extract_tas_df(ric, start, end, token) -> pd.DataFrame:
    headers = {"Authorization": f"Token {token}", "Content-Type": "application/json"}
    resp = requests.post(EXTRACT_URL, headers=headers, data=json.dumps(payload_tas(ric, start, end)))
    if resp.status_code >= 400:
        raise RTHError(f"EXTRACT {resp.status_code}: {resp.text[:1200]}")
    j = resp.json()

    links = _collect_links(j)
    if links:                                           # case 1: URLs to fetch
        frames = []
        for u in links:
            r = requests.get(u, headers=headers, stream=True)
            if r.status_code >= 400:
                raise RTHError(f"DOWNLOAD {r.status_code}: {r.text[:800]}")
            frames.append(_read_zip_or_csv_bytes(r.content))
        return pd.concat(frames, ignore_index=True) if frames else pd.DataFrame()

    job_id = j.get("JobId") or j.get("jobId")
    if job_id:                                          # case 2: a JobId to stream
        return download_stream_by_jobid(token, job_id)

    rows = j.get("Data") or j.get("Rows")               # case 3: rows inline
    if rows is None:
        raise RTHError(f"No links, no JobId, no rows. Body: {str(j)[:1000]}")
    return pd.DataFrame(rows)

The loop skips any window whose file already exists, so a stopped run restarts where it left off. If LSEG does not finish a window in time, the script tries again, and after a few tries, it writes the window to failed_rics.csv.

from pathlib import Path
from datetime import datetime, timedelta
from concurrent.futures import ThreadPoolExecutor, as_completed
from pandas.errors import EmptyDataError
import csv, time

RICS        = rics                                   # from Step 1, or your own list
START       = "2025-05-01T07:00:00.000Z"             # UTC, inclusive
END         = "2025-05-31T23:59:59.000Z"
BASE_DIR    = r"C:\path\to\tick_data"                # output folder
CHUNK_DAYS  = 30                                     # window width per request
MAX_WORKERS = 3                                      # parallel downloads
MAX_RETRIES = 10                                     # per-chunk retries

def daterange_chunks(start_date, end_date, chunk_days):
    """Split a date range into windows of chunk_days, the last one possibly shorter.

    A whole date range in one request can be more than the service will return in one go,
    so each window is asked for separately. CHUNK_DAYS sets the width.
    """
    current = start_date
    while current < end_date:
        window_end = current + timedelta(days=chunk_days)
        yield current, min(window_end, end_date)     # min: never run past the end asked for
        current = window_end

def process_chunk(ric, chunk_start, chunk_end, token):
    """Download one stock over one window, unless its file is already on disk."""
    start_text = chunk_start.strftime("%Y-%m-%dT%H:%M:%S.000Z")
    end_text = chunk_end.strftime("%Y-%m-%dT%H:%M:%S.000Z")
    label = f"{chunk_start.date()}_{chunk_end.date()}"
    out_csv = Path(BASE_DIR) / f"{ric}_{label}.csv"

    if out_csv.exists():
        return {
            "ok": True,
            "msg": f"skip  {ric} [{label}]: already downloaded",
        }
    for attempt in range(1, MAX_RETRIES + 1):
        try:
            df = extract_tas_df(ric, start_text, end_text, token)

            # Write to a .part file and rename it once the write finished. A run killed
            # mid-write then leaves no half-file that the resume check would trust.
            tmp_csv = out_csv.with_suffix(".csv.part")
            df.to_csv(tmp_csv, index=False)
            tmp_csv.replace(out_csv)
            return {
                "ok": True,
                "msg": f"OK    {ric} [{label}]: {len(df):,} rows -> {out_csv}",
            }
        except EmptyDataError:
            return {
                "ok": True,
                "msg": f"empty {ric} [{label}]: no data, skipping",
            }
        except Exception as ex:
            err = f"{type(ex).__name__}: {ex}"
            if attempt < MAX_RETRIES:
                time.sleep(2 * attempt)
                print(
                    f"...   retry {attempt}/{MAX_RETRIES} "
                    f"for {ric} [{label}]: {err}"
                )
                continue
            return {
                "ok": False,
                "ric": ric,
                "chunk": label,
                "error": err,
                "msg": f"FAIL  {ric} [{label}]: {err}",
            }

def main():
    Path(BASE_DIR).mkdir(parents=True, exist_ok=True)
    token = auth_token()

    start_dt = datetime.strptime(START, "%Y-%m-%dT%H:%M:%S.000Z")
    end_dt   = datetime.strptime(END,   "%Y-%m-%dT%H:%M:%S.000Z")

    tasks = [(ric, cs, ce, token)
             for ric in RICS
             for cs, ce in daterange_chunks(start_dt, end_dt, CHUNK_DAYS)]

    failed = []
    with ThreadPoolExecutor(max_workers=MAX_WORKERS) as ex:
        for fut in as_completed(ex.submit(process_chunk, *t) for t in tasks):
            res = fut.result()
            print(res["msg"])
            if not res["ok"]:
                failed.append(res)

    if failed:
        path = Path(BASE_DIR) / "failed_rics.csv"
        with path.open("w", newline="", encoding="utf-8") as f:
            w = csv.writer(f)
            w.writerow(["RIC", "Chunk", "Error"])
            for row in failed:
                w.writerow([row["ric"], row["chunk"], row["error"]])
        print(f"\nSaved {len(failed)} failed chunks to {path}")
    else:
        print("\nNo failed chunks.")

if __name__ == "__main__":
    main()

In my own runs, one month of one active London stock produced millions of rows, and a month of all London stocks can take hours. The login only lasts for 24 hours, so in a longer run, every window after that fails, but there are probably ways to get around that.

Conclusion

So the conclusion is that this is a script for anyone interested in tick data who has access to Tick History and to Workspace if they want to get the ISINs.